package com.zhouyibike.uu.ui.activity.yihoudong;

import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.support.v4.content.ContextCompat;
import android.os.Bundle;
import android.util.Log;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.LimitLine;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.ValueFormatter;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.github.mikephil.charting.utils.Utils;
import com.github.mikephil.charting.utils.ViewPortHandler;
import com.zhouyibike.uu.R;
import com.zhouyibike.uu.ui.base.BaseActivity2;
import com.zhouyibike.uu.utils.Base64Utils;
import com.zhouyibike.uu.utils.PhoneUtils;
import com.zhouyibike.uu.utils.RSAUtils;

import java.security.PrivateKey;
import java.security.PublicKey;
import java.text.DecimalFormat;
import java.util.ArrayList;

public class YihuodongActivity2 extends BaseActivity2 {
    TextView zz;
    LineChart mLineChart;
    /* 密钥内容 base64 code */
    private static String PUCLIC_KEY = "\"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC36fHnM3TqFeppHA3eyWAg8GR80I8YeKS8A3TmgLSRxR3iQ0CErdi4O7Rn5oiF5jyqSr9dTXm6P1dwbPVy//DHMwMJsp5k0EHwSAH7CSG4La1x242fNYxCMFZW3QQSQduStYPNttnl+djT92IvGVL9or4elZt3R7qFgyC8f1XMawIDAQAB\"";
    //    private static String PUCLIC_KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCXiLNbjQVHSmnBp6gROr9QBHW2L73Mp1MU+5tkkptHMpMG9beAEilsIOiHQoRBqIsKIg0gQaZajSt+C/XBENMPFNXY2KDrx5HjQoLqX9i8OZ7hU7kJXBndx9VD3VNYDnCKmP89sdUNcTv6JjubXTVQMrh3wWe/6kZt0KTtzyTrywIDAQAB";
    private static String PRIVATE_KEY = "MIICXAIBAAKBgQC36fHnM3TqFeppHA3eyWAg8GR80I8YeKS8A3TmgLSRxR3iQ0CErdi4O7Rn5oiF5jyqSr9dTXm6P1dwbPVy//DHMwMJsp5k0EHwSAH7CSG4La1x242fNYxCMFZW3QQSQduStYPNttnl+djT92IvGVL9or4elZt3R7qFgyC8f1XMawIDAQABAoGAUHpY1nkX4g8xAkm6cBDitcc70bpZw7WXMIa6stsDKP5+szIGm4iPWx8VNJoWh7FWPpZy4tsyNyPcmV+0kFwa+fEH+YFVNZvKoqWpUY51cyzjJX5iGEEf2PQKpy+qv8+VYhk866/z2Vbmk+oWKrkH0BaSZEUNE/NGY4uhEtfzX2ECQQDxX5uTsked6rEeZOx+4E2Da5rOrr+WglPOtVvMDHt0RPBYZT6ebiCad++/hbB8pv3T9BGUUJb6z+brhLZiCB4JAkEAww75a1QaC6Z56lvz0MR7Vk6+oYoitBZI+HU6movLfEqLvOliHWf+DOoR3QpRKhV8K9GvPnI75zPdXVkona9z0wJBAIYEc7lZ73G68YTSvIzltaQWhunjFPVYf3fyMnnlJFa2QEyUSmRk+S1LEo7gh9FuVtjsVyZmaK3x6WEzWqCrqSECQHo6aOrrgYKpaB4GTssURCE6KNR7BfIJQOKIOxfa38DbyaKwMC4zGwwmpNj4/RE881lWBNVBqe3gHye+lefxqMcCQF1lfNn3A8BH36Nq8lI/bYafvhc4gKK7EM0Ra3exV2cwyLYKSm8/2pdYYggJ65RIFgKJDH4q8uZgsNpbwS8wnGs=";
    String afterencrypt1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
//        {
//            // 透明状态栏
//            getWindow().addFlags( WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
//            SystemBarTintManager tintManager = new SystemBarTintManager(this);
//            // 激活状态栏
//            tintManager.setStatusBarTintEnabled(true);
//        }
        setContentView(R.layout.activity_yihuodong2);


        zz = (TextView) findViewById(R.id.zz);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Log.e("onCreate: ", PhoneUtils.getStatusBarHeight(this) + "");
            RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) zz.getLayoutParams();
            lp.setMargins(0, PhoneUtils.getStatusBarHeight(this), 0, 0);
        }
        String source = "王志刚@@@15131615837@@@10";
//        String source = "丁增宇@@@15733239087@@@10";
        try {
            // 从字符串中得到公钥
            PublicKey publicKey = RSAUtils.loadPublicKey(PUCLIC_KEY);
            Log.e("onCreate: ","PublicExponent=" + Base64Utils.encode(publicKey.getEncoded()) );
            PrivateKey privateKey = RSAUtils.loadPrivateKey(PRIVATE_KEY);
            // 从文件中得到公钥
//            InputStream inPublic = getResources().getAssets().open("rsa_public_key.pem");
//            PublicKey publicKey = RSAUtils.loadPublicKey(inPublic);
            // 加密
            byte[] encryptByte = RSAUtils.encryptByPublicKey(source.getBytes(), publicKey);
            // 为了方便观察吧加密后的数据用base64加密转一下，要不然看起来是乱码,所以解密是也是要用Base64先转换
            String afterencrypt = Base64Utils.encode(encryptByte);
            Log.e("onCreate1: ", afterencrypt);
            afterencrypt1=afterencrypt;
        } catch (Exception e) {
            e.printStackTrace();
        }
//        String after = "Km1wiRoy2lc4vTrAtAP0/ZNemA7Tp21IC77ORtyk7cFGKgIwQsGanLnmYIyYg6swXGeL7qsxwmj13U/KEe1KG2svvfiZe3GIxatw2pj3C11IMoGGuHQUpsmij8KSccmgwcn8Wfe4Un9kOcJYVF9AsuE2cr0E8SJfJnyRNJRERS0=";
//        String after = "iyK2cY6lpeXGzF+VI5WTeWnNRzy9bDg2X2KWdZ/MLaFTf/YaUl0qmq7KERV5yZ6nvojpJR5EgkK0bjVdTOSQibgJHMenaP2A+zWMmsRFhU5YtrceX4by/5fXlmPxQOxekwTIEr9BeuYxkNsnETe+bt/nK8NRhd7CwOWNNlCQVzc=";
        try {
            // 从字符串中得到私钥
            PrivateKey privateKey = RSAUtils.loadPrivateKey(PRIVATE_KEY);
            PublicKey publicKey = RSAUtils.loadPublicKey(PUCLIC_KEY);
            // 从文件中得到私钥
//            InputStream inPrivate = getResources().getAssets().open("pkcs8_rsa_private_key.pem");
//            PrivateKey privateKey = RSAUtils.loadPrivateKey(inPrivate);
            // 因为RSA加密后的内容经Base64再加密转换了一下，所以先Base64解密回来再给RSA解密
            byte[] decryptByte = RSAUtils.decryptByPrivateKey(Base64Utils.decode(afterencrypt1), privateKey);
            String decryptStr = new String(decryptByte);
            Log.e("onCreate2: ", decryptStr);
        } catch (Exception e) {
            e.printStackTrace();
        }

        mLineChart = (LineChart) findViewById(R.id.lineChart);
        initChart();
        setData(7,5);
    }
    //设置chart基本属性
    private void initChart() {
        //描述信息
//        Description description = new Description();
//        description.setText("我是描述信息");
        //设置描述信息
//        mLineChart.setDescription(description);
        //设置没有数据时显示的文本
        mLineChart.setDescription("");
        mLineChart.setNoDataTextDescription("");
        mLineChart.setNoDataText("");
        //设置是否绘制chart边框的线
        mLineChart.setDrawBorders(false);
        //设置chart边框线颜色
        mLineChart.setBorderColor(Color.WHITE);
        //设置chart边框线宽度
        mLineChart.setBorderWidth(1f);
        //设置chart是否可以触摸
        mLineChart.setTouchEnabled(false);
        //设置是否可以拖拽
        mLineChart.setDragEnabled(false);
        //设置是否可以缩放 x和y，默认true
        mLineChart.setScaleEnabled(false);
        //设置是否可以通过双击屏幕放大图表。默认是true
        mLineChart.setDoubleTapToZoomEnabled(false);
        //设置chart动画
        mLineChart.animateXY(1000, 0);

        //=========================设置图例=========================
        // 像"□ xxx"就是图例
        Legend legend = mLineChart.getLegend();
        //设置图例显示在chart那个位置 setPosition建议放弃使用了
        //设置垂直方向上还是下或中
        legend.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
        //设置水平方向是左边还是右边或中
        legend.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT);
        //设置所有图例位置排序方向
        legend.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        //设置图例的形状 有圆形、正方形、线
        legend.setForm(Legend.LegendForm.CIRCLE);
        //是否支持自动换行 目前只支持BelowChartLeft, BelowChartRight, BelowChartCenter
        legend.setWordWrapEnabled(true);
        legend.setEnabled(false);

        //=======================设置X轴显示效果==================
        XAxis xAxis = mLineChart.getXAxis();
        //是否启用X轴
        xAxis.setEnabled(true);
        //是否绘制X轴线
        xAxis.setDrawAxisLine(false);
        xAxis.setTextColor(getResources().getColor(R.color.text_main_3));
        //设置X轴上每个竖线是否显示
        xAxis.setDrawGridLines(false);
        xAxis.setTextSize(9f);
        //设置是否绘制X轴上的对应值(标签)
        xAxis.setDrawLabels(true);
        //设置X轴显示位置
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        //设置竖线为虚线样式
        // xAxis.enableGridDashedLine(10f, 10f, 0f);
        //设置x轴标签数
//        xAxis.setLabelCount(5, true);
        //图表第一个和最后一个label数据不超出左边和右边的Y轴
        // xAxis.setAvoidFirstLastClipping(true);

        //设置限制线 12代表某个该轴某个值，也就是要画到该轴某个值上
        LimitLine limitLine = new LimitLine(12);
        //设置限制线的宽
        limitLine.setLineWidth(1f);
        //设置限制线的颜色
        limitLine.setLineColor(Color.WHITE);
        //设置基线的位置
        limitLine.setLabelPosition(LimitLine.LimitLabelPosition.LEFT_TOP);
        limitLine.setLabel("马丹我是基线，也可以叫我水位线");
        //设置限制线为虚线
//        limitLine.enableDashedLine(10f, 10f, 0f);
        //左边Y轴添加限制线
//        axisLeft.addLimitLine(limitLine);

        //=================设置左边Y轴===============
        YAxis axisLeft = mLineChart.getAxisLeft();
        //是否启用左边Y轴
        axisLeft.setEnabled(true);
        axisLeft.setTextColor(Color.WHITE);
        axisLeft.setGridColor(Color.WHITE);
        axisLeft.setAxisLineColor(Color.WHITE);
        //设置最小值（这里就按demo里固死的写）
//        axisLeft.setAxisMinValue(1);
//        //设置最大值（这里就按demo里固死的写了）
//        axisLeft.setAxisMaxValue(20);
        //设置横向的线为虚线
//        axisLeft.enableGridDashedLine(10f, 10f, 0f);
        //axisLeft.setDrawLimitLinesBehindData(true);


        //====================设置右边的Y轴===============
        YAxis axisRight = mLineChart.getAxisRight();
        //是否启用右边Y轴
        axisRight.setEnabled(true);
        axisRight.setTextColor(Color.WHITE);
        axisRight.setGridColor(Color.WHITE);
        axisRight.setAxisLineColor(Color.WHITE);
        //设置最小值（这里按demo里的数据固死写了）
//        axisRight.setAxisMinValue(1);
//        //设置最大值（这里按demo里的数据固死写了）
//        axisRight.setAxisMaxValue(20);
        //设置横向的线为虚线
//        axisRight.enableGridDashedLine(10f, 10f, 0f);

    }
    public class MyValueFormatter implements ValueFormatter {

        DecimalFormat df = new DecimalFormat("######0.00");
        DecimalFormat df2 = new DecimalFormat("######0");
        @Override
        public String getFormattedValue(float value, Entry entry, int dataSetIndex, ViewPortHandler viewPortHandler) {
            return df.format(value) + "万";
//            return null;
        }
    }
    private void setData(int count, float range) {

        ArrayList<String> xVals = new ArrayList<String>();
        for (int i = 0; i < count; i++) {
            xVals.add((i) + "");
        }
        ArrayList<Entry> yVals = new ArrayList<Entry>();
        for (int i = 0; i < count; i++) {
            float mult = (range + 1);
            float val = (float) (Math.random() * mult) + 3;// + (float)
            // ((mult *
            // 0.1) / 10);
            yVals.add(new Entry(val, i));
        }

        LineDataSet set1;

        if (mLineChart.getData() != null &&
                mLineChart.getData().getDataSetCount() > 0) {
            set1 = (LineDataSet)mLineChart.getData().getDataSetByIndex(0);
            set1.setYVals(yVals);
            mLineChart.getData().setXVals(xVals);
            mLineChart.notifyDataSetChanged();
        } else {
            // create a dataset and give it a type
            set1 = new LineDataSet(yVals, "DataSet 1");

            // set1.setFillAlpha(110);
            // set1.setFillColor(Color.RED);

            // set the line to be drawn like this "- - - - - -"
//            set1.enableDashedLine(10f, 5f, 0f);
//            set1.enableDashedHighlightLine(10f, 5f, 0f);
            set1.setColor(getResources().getColor(R.color.radio_button_selected_color));
            set1.setCircleColor(getResources().getColor(R.color.radio_button_selected_color));
            set1.setValueTextColor(getResources().getColor(R.color.zhexiantutvvalue));
            set1.setValueFormatter(new MyValueFormatter());
            set1.setLineWidth(4f);
            set1.setCircleRadius(5f);
            set1.setCircleHoleRadius(3.5f);
            set1.setDrawCircleHole(true);
            set1.setValueTextSize(12f);
            set1.setDrawFilled(true);

            if (Utils.getSDKInt() >= 18) {
                // fill drawable only supported on api level 18 and above
                Drawable drawable = ContextCompat.getDrawable(this, R.drawable.fade_red);
                set1.setFillDrawable(drawable);
            }
            else {
                set1.setFillColor(Color.WHITE);
            }

            ArrayList<ILineDataSet> dataSets = new ArrayList<ILineDataSet>();
            dataSets.add(set1); // add the datasets

            // create a data object with the datasets
            LineData data = new LineData(xVals, dataSets);

            // set data
            mLineChart.setData(data);
        }
    }
}
